import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import DataBase from 'src/config/database';
import { DeleteResult, In, IsNull, Not, Repository } from 'typeorm';
import { Answer } from './answer.entity';
import utils from 'src/common/utils';
import { Video } from '../video/video.entity';

@Injectable()
export class AnswerServiceManager {
  constructor(
    @InjectRepository(Answer)
    private repository: Repository<Answer>,
    @InjectRepository(Video)
    private videoRepository: Repository<Video>
  ) {}

  async findAnswerCheckNotNullByVideo(skip:number, take: number, video_id: number): Promise<{dataList: [], total: Number}>{
    let dataList = await this.repository.query(`
      select answer.id,answer_info.platform,answer_info.account,answer_info.avatar_img,answer_info.ic_name,answer_info.img,answer.id_card,answer.create_time, answer.ic_group
      from answer_info
      inner join (
        select * from answer
        where answer.video_id = ? and answer.check is null
        limit ?,?
      ) answer on answer.id = answer_info.answer_id
      order by answer.create_time asc
    `,[video_id, skip, take])
    dataList.map(e => {
      if(e.create_time){
        e.create_time = utils.Format(e.create_time, 'yyyy-MM-dd hh:mm:ss')
      }
    })

    //查询答案关联网红的数据
    let dataList_RelaIc = await this.repository.query(`
      select answer.id, answer.id_card, answer.create_time, platform.platform, internet_celebrity.account, internet_celebrity.name as ic_name,internet_celebrity.avatar_img, 
        internet_celebrity.img
      from internet_celebrity
      inner join platform on platform.id = internet_celebrity.platform
      inner join (
        select * from answer
        where answer.video_id = ? and answer.check is null
        limit ?,?
      ) answer on answer.ic_group = internet_celebrity.ic_group
      where platform.platform is not null and platform.platform != ''
      order by answer.create_time asc
    `,[video_id, skip, take])

    dataList_RelaIc.map(e => {
      let findAnswerInfo = dataList.find(c => c.id == e.id)
      if(findAnswerInfo){
        if(!findAnswerInfo.ic_info){
          findAnswerInfo.ic_info = e
        }else{
          let addVideo = JSON.parse(JSON.stringify(findAnswerInfo))
          addVideo.ic_info = e
          dataList.push(addVideo)
        }
      }
    })
    dataList.filter(e => !e.ic_info).map(e => {
      e.ic_info = JSON.parse(JSON.stringify(e))
    })
    let total = await this.repository.count({where:{video_id: video_id, check: IsNull()}})
    return {
      dataList: dataList,
      total: total
    }
  }

  async changeAnswerIcGroup(answer_id: number, ic_group: number): Promise<any> {
    //查询答案详情
    let findAnswer = await this.repository.findOne({where:{id:answer_id}})
    if(!findAnswer){
      return '答案不存在'
    }
    let video_id: number = findAnswer.video_id
    //查询视频/图片
    let findVideo = await this.videoRepository.findOne({where:{id:video_id}})
    if(!findVideo){
      return '视频不存在'
    }

    let db: DataBase = new DataBase()
    let connection = await db.getConnection()
    const queryRunner = connection.createQueryRunner()
    await queryRunner.connect()
    // 开始事务
    await queryRunner.startTransaction()
    try {
      await this.repository.createQueryBuilder(null,queryRunner).update({ic_group: ic_group})
        .where({id: answer_id}).execute()

      //视频关联网红
      // let updateVideoParams:any = { ic_group: ic_group }
      // await this.videoRepository.createQueryBuilder(null,queryRunner)
      //   .update(updateVideoParams)
      //   .where({ id: video_id}).execute()

      await queryRunner.commitTransaction()
      await queryRunner.release();
    } catch (err) {
      // 有错误做出回滚更改
      await queryRunner.rollbackTransaction()
      await queryRunner.release();
      return err
    }
  }
  
  async clearAnswerIcGroup(answer_id: number): Promise<any> {
    //查询答案详情
    let findAnswer = await this.repository.findOne({where:{id:answer_id}})
    if(!findAnswer){
      return '答案不存在'
    }
    let video_id: number = findAnswer.video_id
    //查询视频/图片
    let findVideo = await this.videoRepository.findOne({where:{id:video_id}})
    if(!findVideo){
      return '视频不存在'
    }

    let db: DataBase = new DataBase()
    let connection = await db.getConnection()
    const queryRunner = connection.createQueryRunner()
    await queryRunner.connect()
    // 开始事务
    await queryRunner.startTransaction()
    try {
      await this.repository.createQueryBuilder(null,queryRunner).update({ic_group: null})
        .where({id: answer_id}).execute()

      //视频关联网红
      await this.videoRepository.createQueryBuilder(null,queryRunner)
        .update({ic_group: null})
        .where({ id: video_id}).execute()

      await queryRunner.commitTransaction()
      await queryRunner.release();
    } catch (err) {
      // 有错误做出回滚更改
      await queryRunner.rollbackTransaction()
      await queryRunner.release();
      return err
    }
  }
}
